package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
)

var (
	command        string
	args           []string
	outDir         string
	outDirFileMode os.FileMode
)

func init() {
	if len(os.Args) > 1 {
		command = os.Args[1]
	}
	var nextOutput bool
	for i, arg := range os.Args {
		if i <= 1 {
			continue
		}
		if nextOutput {
			dir, name := filepath.Split(arg)
			ext := filepath.Ext(name)
			if ext == "" {
				name = "lib" + name + ".a"
			}
			outDir = dir
			fileInfo, err := os.Stat(dir)
			if os.IsNotExist(err) {
				err = os.MkdirAll(dir, os.FileMode(0777))
				if err != nil {
					return
				}
				fileInfo, _ = os.Stat(dir)
			}
			if fileInfo == nil {
				return
			}
			fileMode := fileInfo.Mode()
			outDirFileMode = fileMode
			if uint(fileMode.Perm())&0200 <= 0 {
				err = os.Chmod(dir, os.FileMode(uint(fileMode.Perm())|0200))
				if err != nil {
					return
				}
			}
			arg = filepath.Join(dir, name)
			nextOutput = false
		}
		if arg == "-o" {
			nextOutput = true
		}
		args = append(args, arg)
	}
}
func main() {
	if command != "" {
		cmd := exec.Command(command, args...)
		err := cmd.Start()
		if err != nil {
			fmt.Println(err)
		}
		err = cmd.Wait()
		if err != nil {
			fmt.Println(err)
		}
		err = os.Chmod(outDir, outDirFileMode)
		if err != nil {
			return
		}
	}
}
